package com.maodou.android.ui.page.login

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Email
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.maodou.android.R
import com.maodou.android.ui.page.ContactKey
import com.maodou.android.ui.page.ForgotKey
import com.maodou.android.ui.page.RegisterKey
import com.maodou.android.viewmodel.login.LoginViewModel
import com.maodou.core.navigation.Navigator3
import com.maodou.core.ui.components.HSpacer
import com.maodou.core.ui.components.VSpacer
import com.maodou.core.ui.components.debouncedClickable
import com.maodou.core.ui.components.textfield.AppTextField
import com.maodou.core.ui.components.textfield.TextFieldStyles

/**
 * 登录页面 UI
 */
@Composable
fun LoginScreen(
    viewModel: LoginViewModel = hiltViewModel(),
) {
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()
    var email by rememberSaveable { mutableStateOf("") }
    var password by rememberSaveable { mutableStateOf("") }
    var passwordVisible by rememberSaveable { mutableStateOf(false) }

    Column (modifier = Modifier.fillMaxSize().background(Color(0xffFCFCFD)).verticalScroll(rememberScrollState())) {

        LoginTopLogo()

        Surface(
            modifier = Modifier.fillMaxWidth().padding(20.dp),
            shape = RoundedCornerShape(24.dp),
            color = MaterialTheme.colorScheme.surface,
            shadowElevation = 1.dp
        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 20.dp),
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                Spacer(Modifier.height(24.dp))

                Text(
                    text = "登录",
                    style = MaterialTheme.typography.headlineSmall,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colorScheme.onSurface
                )

                AppTextField(
                    value = email,
                    onValueChange = { email = it },
                    label = "邮箱",
                    placeholder = "请输入邮箱",
                    leadingIcon = Icons.Default.Email,
                    keyboardOptions = KeyboardOptions(
                        keyboardType = KeyboardType.Email,
                        imeAction = ImeAction.Next
                    ),
                    colors = TextFieldStyles.filled(),
                    modifier = Modifier.fillMaxWidth().background(color = Color(0xffFAFAF9), shape = RoundedCornerShape(6.dp)),
                    borderless = true
                )

                Box {
                    AppTextField(
                        value = password,
                        onValueChange = { password = it },
                        label = "密码",
                        placeholder = "请输入密码",
                        leadingIcon = Icons.Default.Lock,
                        onTrailingIconClick = { passwordVisible = !passwordVisible },
                        singleLine = true,
                        keyboardOptions = KeyboardOptions(
                            keyboardType = KeyboardType.Password,
                            imeAction = ImeAction.Done
                        ),
                        visualTransformation = if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(),
                        colors = TextFieldStyles.filled(),
                        modifier = Modifier
                            .fillMaxWidth().background(color = Color(0xffFAFAF9), shape = RoundedCornerShape(6.dp)),
                        borderless = true
                    )

                    Row(modifier = Modifier.align(Alignment.CenterEnd).height(40.dp).padding(end = 12.dp).debouncedClickable {
                        Navigator3.navigate(ForgotKey)
                    }, verticalAlignment = Alignment.CenterVertically) {
                        Text(
                            text = "忘记密码",
                            style = MaterialTheme.typography.labelLarge,
                            color = MaterialTheme.colorScheme.primary,
                            modifier = Modifier
                        )
                    }
                }
                VSpacer(12.dp)
                Button(
                    onClick = { viewModel.onLogin(email, password) },
                    enabled = !uiState.isLoading,
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(52.dp),
                    shape = RoundedCornerShape(16.dp)
                ) {
                    if (uiState.isLoading) {
                        CircularProgressIndicator(
                            modifier = Modifier.size(16.dp),
                            strokeWidth = 2.dp,
                            color = MaterialTheme.colorScheme.onSecondary
                        )
                        HSpacer(4.dp)
                        Text(text = "登录中...", textAlign = TextAlign.Center, color = MaterialTheme.colorScheme.onSecondary)
                    } else Text(text = "登录", textAlign = TextAlign.Center)
                }

                VSpacer(12.dp)

                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 24.dp),
                    horizontalArrangement = Arrangement.Center
                ) {
                    Text(
                        text = "没有账号？",
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    Spacer(Modifier.width(8.dp))
                    Text(
                        text = "立即注册",
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.primary,
                        textDecoration = TextDecoration.Underline,
                        modifier = Modifier.debouncedClickable {
                            Navigator3.navigate(RegisterKey)
                        }
                    )
                }
            }
        }

        Spacer(modifier = Modifier.weight(1f))
        VSpacer(32.dp)
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.Center
        ) {
            Text(
                text = "联系我们",
                style = MaterialTheme.typography.labelLarge,
                color = MaterialTheme.colorScheme.onSurface,
                modifier = Modifier
                    .padding(16.dp)
                    .debouncedClickable {
                        Navigator3.navigate(ContactKey)
                    },
                textDecoration = TextDecoration.Underline
            )
        }
        VSpacer(16.dp)
    }
}

@Composable
fun LoginTopLogo(){
    Column(
        modifier = Modifier.fillMaxWidth().padding(top = 48.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Image(
            painter = painterResource(R.mipmap.ic_logo),
            contentDescription = "logo",
            modifier = Modifier
        )
        VSpacer(10.dp)
        Text(
            text = stringResource(R.string.app_name),
            color = Color(0xff3F464E),
            fontWeight = FontWeight.Bold,
            fontSize = 28.sp
        )
        VSpacer(10.dp)
        Text(
            //打开你的社交世界
            //
            //一把钥匙，登录所有账号
            // 你的跨平台账号，一证通行
            //一键管理多个社交账号
            //登录，从此更简单

            text = "一把钥匙，登录所有账号",
            color = Color(0xff998D91),
            fontWeight = FontWeight.W400,
            fontSize = 16.sp
        )
    }

}

@Preview(showBackground = true)
@Composable
fun LoginScreenPreview() {
    LoginScreen()
}